import axios from 'axios'
import type { AxiosRequestConfig, AxiosResponse, AxiosRequestHeaders } from 'axios'
import { message } from 'antd'
import { useStore } from './store'

const api = axios.create({
  baseURL: '', // 替换为实际API地址
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 添加Token
api.interceptors.request.use((config) => {
  const { tokenInfo } = useStore.getState()
  if (tokenInfo?.access_token) {
    config.headers = {
      ...config.headers,
      Authorization: `Bearer ${tokenInfo.access_token}`
    } as AxiosRequestHeaders
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器 - 处理错误
api.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, message: msg } = response.data
    if (code !== 0) {
      message.error(msg || '请求失败')
      return Promise.reject(response.data)
    }
    return response.data
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          message.error('登录已过期，请重新登录')
          useStore.getState().logout()
          window.location.href = '/login'
          break
        case 403:
          message.error('无权限访问')
          window.location.href = '/no-permission'
          break
        default:
          message.error(error.response.data?.message || '请求错误')
      }
    }
    return Promise.reject(error)
  }
)

// 登录接口
export const login = function  (username: string, password: string) :Promise<any>
 {
  
    return  api.post('/api/AbpFundation/User/login', { username, password })
  
}

// 其他API接口
export const fetchUser = async (userId: number): Promise<{name: string; email: string}> => {
  const response = await api.get(`/users/${userId}`)
  return {
    name: response.data.name,
    email: response.data.email
  }
}
